package main

import "crypto/sha256"

// 定义区块
type Block struct {
	//前一个哈希
	PrevHash []byte
	//当前区块哈希
	Hash []byte
	//交易数据
	Data []byte
}

// 创建区块
func (blockChain *BlockChain) NewBlock(data string) *Block {
	blocks := blockChain.Blocks
	prevBlockHash := []byte{}
	if len(blocks) > 0 {
		prevBlockHash = blocks[(len(blocks) - 1)].Hash
	}

	block := &Block{
		PrevHash: prevBlockHash,
		Data:     []byte(data),
	}
	block.SetHash()
	return block
}

// 生成哈希
func (block *Block) SetHash() {
	blockInfo := append(block.PrevHash, block.Data...)
	hash := sha256.Sum256(blockInfo)
	block.Hash = hash[:]
}
